const { promisify } = require("util");
const { program } = require("commander"); // 命令行工具
const { VUE_REPO } = require("../config/repo"); // 仓库Vue模板地址
const compileEjs = require("../utils/compile-ejs");
const execCommand = require("../utils/exec-command");
const writeFile = require("../utils/write-file");

const download = promisify(require("download-git-repo")); // 下载模板

// 创建项目命令
async function createProjectAction(project) {
  try {
    // 1. 从编写的项目模板中clone下来项目
    await download(VUE_REPO, project, { clone: true });

    // 2. 很多的脚手架, 都是在这里给予命令提示
    // console.log(`cd ${project}`);
    // console.log(`npm install`);
    // console.log(`npm run serve`);

    // 3. 帮助执行 npm install
    console.log(process.platform); // win32
    const commandName = process.platform === "win32" ? "npm.cmd" : "npm";
    await execCommand(commandName, ["install"], { cwd: `./${project}` }); // { cwd: `./${project}` } 指定目录

    // 4. 帮助执行npm run dev
    await execCommand(commandName, ["run", "dev"], { cwd: `./${project}` }); // { cwd: `./${project}` } 指定目录
  } catch (error) {
    console.log("github下载失败", error);
  }
}

// 添加组件命令
async function addComponentAction(cpnname) {
  // 1. 创建一个组件: 编写组件的模板, 根据内容给模板中填充数据
  const result = await compileEjs("component.vue.ejs", {
    name: cpnname,
    lowername: cpnname.toLowerCase(), // 组件名称小写
  });

  // 2. 将result写到对应的文件夹中
  const dest = program.opts().dest || "src/components";
  await writeFile(`${dest}/`, `${cpnname}.vue`, result, {
    encoding: "utf-8",
    flag: "a", // 追加模式
  });
  console.log("创建组件成功: ", cpnname + ".vue");
}

module.exports = {
  createProjectAction,
  addComponentAction,
};
